package io.renren.modules.live.service.impl;

import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserTokenEntity;
import io.renren.modules.sys.oauth2.TokenGenerator;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.live.dao.FanweUserTokenDao;
import io.renren.modules.live.entity.FanweUserTokenEntity;
import io.renren.modules.live.service.FanweUserTokenService;


@Service("fanweUserTokenService")
public class FanweUserTokenServiceImpl extends ServiceImpl<FanweUserTokenDao, FanweUserTokenEntity> implements FanweUserTokenService {
    //12小时后过期
    private final static int EXPIRE = 3600 * 12;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FanweUserTokenEntity> page = this.page(
                new Query<FanweUserTokenEntity>().getPage(params),
                new QueryWrapper<FanweUserTokenEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public R createToken(Long userId) {
        //生成一个token
        String token = "usr"+TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

        //判断是否生成过token
        FanweUserTokenEntity tokenEntity = this.getById(userId);
        if(tokenEntity == null){
            tokenEntity = new FanweUserTokenEntity();
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            this.save(tokenEntity);
        }else{
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            this.updateById(tokenEntity);
        }

        R r = R.ok().put("token", token).put("expire", EXPIRE).put("userId",userId);

        return r;
    }

    @Override
    public void logout(Long userId) {
        //生成一个token
        String token = "usr"+TokenGenerator.generateValue();

        //修改token
        FanweUserTokenEntity tokenEntity = new FanweUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        this.updateById(tokenEntity);
    }

}